/*
 * @(#)DocumentExtraInfoTag.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.taglib;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TryCatchFinally;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.util.ResponseUtils;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.WebUtil;

/**
 * Tag to generate extra info for DmsDocument.
 * 
 * @author   Brook.Huang
 * @company  DCIVision Limited
 * @creation date 06/04/2007
 * @version  $Revision: 1.1.2.4 $
 */
public class DocumentExtraInfoTag extends BodyTagSupport implements TryCatchFinally {

  private static final Log LOG = LogFactory.getLog(DocumentExtraInfoTag.class);

  public static String PARENT_SHORTCUT_LINK = "PARENT_SHORTCUT_LINK";

  private DocumentRetrievalManager docRetrievalManager = null;

  private DmsDocument dmsDocument = null;

  private Integer dmsDocumentID = null;

  private String[][] showItems = null;

  public DocumentExtraInfoTag() {
    super();
  }

  protected void initTag() {
    docRetrievalManager = new DocumentRetrievalManager((SessionContainer) pageContext.getSession().getAttribute(
        GlobalConstant.SESSION_CONTAINER_KEY), (Connection) pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY));
  }

  /**
   * Lookup and init the DmsDocument.
   */
  protected void lookupBean() throws JspException {

    // Using the given dmsDocument.
    if (!Utility.isEmpty(dmsDocument)) {
      return;
    }

    // Fetch dmsDocument by given dmsDocumentID.
    if ((!Utility.isEmpty(dmsDocumentID)) && (dmsDocumentID.intValue() > 0)) {

      try {
        dmsDocument = docRetrievalManager.getDocumentByID(dmsDocumentID);
      } catch (ApplicationException ae) {
        LOG.error("Error occurs at fetching document from docRetrievalManager.", ae);
        throw new JspException("Error occurs at fetching document from docRetrievalManager.", ae);
      }

      if (!Utility.isEmpty(dmsDocument)) {
        return;
      }
    }

    // Fetch dmsDocument from page context.
    dmsDocument = (DmsDocument) pageContext.getAttribute(DmsOperationConstant.DMS_DOCUMENT_BEAN);

    if (Utility.isEmpty(dmsDocument)) {
      throw new JspException("Cannt find any dms document for document extra tag.");
    }
  }

  public int doEndTag() throws JspException {
    if (Utility.isEmpty(showItems)) {
      return EVAL_PAGE;
    }

    StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < showItems.length; i++) {
      String[] item = showItems[i];

      if (PARENT_SHORTCUT_LINK.equals(item[0])) {
        buffer.append(renderParentShortcut(item[1]));
      }

    }
    
    ResponseUtils.write(pageContext, buffer.toString());

    return EVAL_PAGE;
  }

  public int doStartTag() throws JspException {
    initTag();
    lookupBean();
    return SKIP_BODY;
  }

  protected String renderParentShortcut(String icon) throws JspException {
    StringBuffer buffer = new StringBuffer();
    
    String link = "";
    String linkLabel = "";

    try {
      boolean isPersonalFolder = DmsRoot.PERSONAL_ROOT.equals(docRetrievalManager.getDmsRoot(dmsDocument.getRootID()).getRootType());
      DmsDocument parentDmsDocument = docRetrievalManager.getDocument(dmsDocument.getParentID());
      SessionContainer sessionContainer = (SessionContainer) pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
      
      if (Utility.isEmpty(parentDmsDocument)) {
        return (GlobalConstant.EMPTY_FIELD);
      }
      
      PermissionManager permissionManager = ((SessionContainer) pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY))
          .getPermissionManager();

      if (icon != null) {
        linkLabel = "<img src=\"" + WebUtil.getImage(pageContext.getRequest(), icon) + "\" align=\"absmiddle\"/>";
      } else {
        linkLabel = parentDmsDocument.getDocumentName();
      }
      
      if (isPersonalFolder) {
        link = ((HttpServletRequest) pageContext.getRequest()).getContextPath() + "/dms/ListDmsDocument.do?rootID=" + dmsDocument.getRootID() + "&parentID=" + parentDmsDocument.getID() + "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER;           
      } else {
        boolean permissionChecked = (permissionManager.hasAccessRight(GlobalConstant.OBJECT_TYPE_DOCUMENT, parentDmsDocument.getID(),PermissionManager.READ_PERMISSION)
            && (!parentDmsDocument.isExpired() || ((SessionContainer) pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY)).getUserRecordID().equals(dmsDocument.getOwnerID())));
        
        if (permissionChecked) {
          link = ((HttpServletRequest) pageContext.getRequest()).getContextPath() + "/dms/ListDmsPublicDocument.do?rootID=" + dmsDocument.getRootID() + "&parentID=" + parentDmsDocument.getID() + "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER;           
        }
      }
      
      if (!Utility.isEmpty(link)) {
        buffer.append(
            "<a " +
            "  href=\""
                 + link +
                 "\" " +
            "  onmouseover=\"return getDocumentInfo('"
                 + TextUtility.escapeJSString(MessageResourcesFactory.getMessage(
                     sessionContainer.getSessionLocale(), "dms.label.folder_path") + " : "
                     + docRetrievalManager.getLocationPath(dmsDocument.getParentID())) +
                 "')\"" +
            "  onmouseout=\"return nd()\"" +
            ">"
            );
      }
      
      buffer.append(linkLabel);
      
      if (!Utility.isEmpty(link)) {
        buffer.append("</a>");
      }
      
      return (buffer.toString());
    } catch (ApplicationException ae) {
      LOG.error("Error occurs at fetching document from docRetrievalManager.", ae);
      throw new JspException("Error occurs at fetching document from docRetrievalManager.", ae);
    }
  }

  public void release() {
    super.release();
    docRetrievalManager = null;
    dmsDocument = null;
    dmsDocumentID = null;
    showItems = null;
  }

  public void doCatch(Throwable t) throws Throwable {
    LOG.error("Error occurred!", t);
    throw t;
  }

  public void doFinally() {
    release();
  }

  /**
   * @return the dmsDocument
   */
  public DmsDocument getDmsDocument() {
    return dmsDocument;
  }

  /**
   * @param dmsDocument the dmsDocument to set
   */
  public void setDmsDocument(DmsDocument dmsDocument) {
    this.dmsDocument = dmsDocument;
  }

  /**
   * @return the dmsDocumentID
   */
  public Integer getDmsDocumentID() {
    return dmsDocumentID;
  }

  /**
   * @param dmsDocumentID the dmsDocumentID to set
   */
  public void setDmsDocumentID(Integer dmsDocumentID) {
    this.dmsDocumentID = dmsDocumentID;
  }

  /**
   * @return the showItems
   */
  public String[][] getShowItems() {
    return showItems;
  }

  /**
   * @param showItems the showItems to set
   */
  public void setShowItems(String[][] showItems) {
    this.showItems = showItems;
  }

}
